package com.shizhen.aidemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

/**
 * Redis配置类
 */
@Configuration
public class RedisConfiguration {

    /**
     * 配置RedisTemplate以支持消息存储
     *
     * @param factory Redis连接工厂，用于创建与Redis服务器的连接
     * @param builder 用于构建ObjectMapper的工具类，此处未使用
     * @return 配置好的RedisTemplate实例
     */
    @Bean
    public RedisTemplate<String, Object> messageRedisTemplate(RedisConnectionFactory factory, Jackson2ObjectMapperBuilder builder) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);

        //使用String序列化器作为key的序列化方式
        template.setKeySerializer(new StringRedisSerializer());
        //对value进行序列化
        template.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));

        //设置hash类型的key和value序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));

        template.afterPropertiesSet();
        return template;
    }
}

